package cn.ihrm.sass.service;

import cn.ihrm.sass.dao.DepartmentDao;
import cn.ihrm.sass.entity.company.Department;
import cn.service.BaseService;
import cn.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/7/1 14:44
 */
@Service
public class DepartmentService extends BaseService {

    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private IdWorker idWorker;

    /**
     * 添加部门信息
     *
     * @param department
     */
    public void save(Department department) {
        // 使用雪花算法生成id
        String id = idWorker.nextId()+"";
        department.setId(id);
        // 进行保存
        department.setCreateTime(new Date());
        departmentDao.save(department);
    }

    /**
     * 修改部门信息
     *
     * @param department
     */
    public void update(Department department) {
        // 先查询再 修改
        Department department1 = departmentDao.findById(department.getId()).get();

        // 修改这几项
        department1.setCity(department.getCity());
        department1.setName(department.getName());
        department1.setCategory(department.getCategory());
        departmentDao.save(department1);
    }

    /**
     * 根据id查询部门信息
     *
     * @param id
     * @return
     */
    public Department findById(String id) {
        // 必须使用get方法
        return departmentDao.findById(id).get();
    }

    /**
     * 根据id删除部门信息
     *
     * @param id
     */
    public void deleteById(String id) {
        departmentDao.deleteById(id);
    }

    /**
     * 查询所有部门信息
     *
     * @return
     */
    public List<Department> findAllDepartment(String companyId) {
        /**
         * 用户构造查询条件
         *  root : 包含了所有的对象数据
         *  cq   : 一般不用
         *  cb   : 构造查询条件
          */
        //Specification<Department> spec = new Specification<Department>() {
        //    @Override
        //    public Predicate toPredicate(Root<Department> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
        //        // 根据企业id查询
        //        return cb.equal(root.get("companyId").as(String.class), companyId);
        //    }
        //
        //};

        return departmentDao.findAll(getSpec(companyId));
    }
}
